package pl.sar.auth.server.ejb.beans.impl;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.RollbackException;
import javax.transaction.UserTransaction;

import org.apache.log4j.Logger;

import pl.sar.auth.server.ejb.beans.IClientService;
import pl.sar.auth.server.ejb.entities.Project;
import pl.sar.auth.server.ejb.entities.User;
import pl.sar.auth.server.ejb.exceptions.UserException;

@Stateless( name = "ClientBean" )
@TransactionManagement(TransactionManagementType.BEAN)
public class ClientService implements IClientService
{
    private static Logger logger = Logger.getLogger( ProjectService.class );

    @PersistenceContext( unitName = "sar-pu" )
    private EntityManager em;

    @Resource
    private UserTransaction utx;
    
    @Override
    public void createUser( String name, String mail, Long projectId ) throws UserException
    {
        try
        {
        	logger.info( "Registering user " + name + " ..." );
        	
        	utx.begin();

            Project project = em.find( Project.class, projectId );
            
            User user = new User();
            user.setName(name);
            user.setMail(mail);
            
            project.addUser(user);
            
            utx.wait(1000);
            
            em.persist( user );
        	
            utx.commit();
        	
        	
            logger.info( "User "+ name +" registered !" );

        }
        catch( RollbackException e )
        {
        	String message = "Cannot create user '" + name + "'." + e.getMessage();
            logger.error( message );
            throw new UserException(message);
        }
        catch(Exception e)
        {
        	logger.error( "Fatal errorr! " + e.getMessage(), e );
        }

    }
}
